package com.dstation.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dstation.domain.*;
import com.dstation.mq.producer.BrowserMqProducer;
import com.dstation.service.interf.IClassificationService;
import com.dstation.service.interf.ITagService;
import com.dstation.service.interf.IUserService;
import com.dstation.service.interf.IVideoService;
import com.dstation.utils.JsonUtil;
import com.dstation.utils.MQConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Controller
@Slf4j
@RequestMapping(value = "/video")
public class VideoController {

    @Autowired
    private IVideoService videoService;

    @Autowired
    private ITagService tagService;

    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private IUserService userService;


    @Resource
    private BrowserMqProducer browserMqProducer;
    /**
     * 上传视频界面
     */
    @RequestMapping(value = "/uploadVideoPage")
    public String uploadVideoPage(ModelMap modelMap) {
        //1. 查询全部的标签信息放入modelMap
        List<TagInfo> labelInfoList = tagService.findAllTagInfo();
        modelMap.put("labelInfoList", labelInfoList);
        //2. 查询全部的类别信息放入modelMap
        List<ClassificationInfo> classificationInfoList = classificationService.findAllClassification();
        modelMap.put("classificationInfoList", classificationInfoList);
        return "main/upload";
    }

    /**
     * 根据父ID查询全部的子类
     */
    @RequestMapping(value = "getClassificationByParentId")
    @ResponseBody
    public JSONObject getClassificationByParentId(@RequestParam("parentId") int parentId)  {
        List<ClassificationInfo> classificationInfoList = classificationService.findClassificationByParentId(parentId);
        JSONObject jsonObject = new JSONObject();
        if(classificationInfoList == null) {   //没有数据，显示空
            jsonObject.put("res", "null");
        } else {
            jsonObject.put("res", "success");
            jsonObject.put("data", JsonUtil.serialize(classificationInfoList));
        }
        return jsonObject;
    }

    /**
     * 上传视频
     * @param videoFile
     * @param coverageFile
     * @param videoTitle
     * @param description
     * @param mainCategoryID
     * @param secondaryCategoryID
     * @param isFree
     * @param labelList
     * @param videoTime
     * @param session
     * @return
     */
    @RequestMapping("/saveVideoInfo")
    @ResponseBody
    public JSONObject saveVideoInfo(@RequestParam("videoFile") MultipartFile videoFile,
                                    @RequestParam("coverageFile")MultipartFile coverageFile,
                                    @RequestParam("videoTitle")String videoTitle,
                                    @RequestParam("description")String description,
                                    @RequestParam("mainCategoryID")int mainCategoryID,
                                    @RequestParam("secondaryCategoryID")int secondaryCategoryID,
                                    @RequestParam("isFree")boolean isFree,
                                    @RequestParam("labelList")String labelList,
                                    @RequestParam("videoTime")int videoTime,
                                    HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        //1. 将视频文件、封面文件上传到磁盘
        String videoFilePath = "D:/dStationData/video/";
        String coverageImgFile = "D:/dStationData/coverageImg/";
        File videoFileDir = new File(videoFilePath);
        if(!videoFileDir.exists()) {
            videoFileDir.mkdir();
        }
        File coverageImgFileDir = new File(coverageImgFile);
        if(!coverageImgFileDir.exists()) {
            coverageImgFileDir.mkdir();
        }
        String newVideoFileName = System.currentTimeMillis() + "_" + "videoFile.mp4";   //因为规定了为mp4文件，因此不需要动态获取后缀
        File destVideoFile = new File(videoFilePath + newVideoFileName);
        try{
            videoFile.transferTo(destVideoFile);
        }catch (Exception e) {
            e.printStackTrace();
        }
        String originalFileName = coverageFile.getOriginalFilename();
        String coverageSuffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String newCoverageImgName = System.currentTimeMillis() + "_" + "coverageImg" + coverageSuffix;
        System.out.println(newCoverageImgName);
        File destCoverageImgFile = new File(coverageImgFile + newCoverageImgName);
        try{
            coverageFile.transferTo(destCoverageImgFile);
        }catch (Exception e) {
            e.printStackTrace();
        }
        //2. 将video信息存入数据库
        VideoInfo videoInfo = new VideoInfo();
        videoInfo.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
        videoInfo.setVideoClassId(secondaryCategoryID);
        videoInfo.setVideoURL(newVideoFileName);
        videoInfo.setVideoTitle(videoTitle);
        videoInfo.setVideoDescription(description);
        videoInfo.setVideoDuration(videoTime);
        videoInfo.setVideoCoverImg(newCoverageImgName);
        videoInfo.setVideoViewNum(0);
        videoInfo.setVideoShareNum(0);
        videoInfo.setFree(isFree);
        videoInfo.setIsPass(false);
        videoInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
        boolean saveRes = videoService.addVideoInfo(videoInfo);
        System.out.println(videoInfo);
        if(saveRes == false) {
            jsonObject.put("res", "error");
            return jsonObject;
        }
        //3. 查询标签ID并插入标签关系
        String[] strArr = labelList.split("\\|");
        ArrayList<TagInfo> labelInfoList = new ArrayList<TagInfo>();
        TagInfo labelInfo = null;
        for(int i = 0; i < strArr.length; i++) {
            labelInfo = tagService.findTagInfoByTagName(strArr[i]);
            labelInfoList.add(labelInfo);
        }
        System.out.println(labelInfoList);
        saveRes = videoService.addVideoTagInfo(labelInfoList, videoInfo.getVideoId(), new Timestamp(System.currentTimeMillis()));
        if(saveRes == false) {
            jsonObject.put("res", "error");
            return jsonObject;
        }
        jsonObject.put("res", "success");
        return jsonObject;
    }

    /**
     * 个人视频界面
     * @return
     */
    @RequestMapping(value = "/myVideoPage")
    public String myVideoPage(@RequestParam(value = "page")Integer page,HttpSession session,ModelMap modelMap){
        UserInfo userInfo=(UserInfo) session.getAttribute("userInfo");
        page = page==null?1:page;
        IPage<VideoInfo> videoList = videoService.findMyVideo(new Page<VideoInfo>(page,10), userInfo.getUserId());
        modelMap.put("videoPageInfo",videoList);
        return "main/myVideo";
    }

    /**
     * 查看视频封面
     * @param videoId
     * @param request
     * @param response
     */
    @RequestMapping("/getVideoCoverageImgById")
    public void getVideoCoverageImgById(@RequestParam("videoId")long videoId, HttpServletRequest request, HttpServletResponse response) {
        String coverageImgFilePath = "D:/dStationData/coverageImg/";
        String coverageImgName = videoService.findVideoCoverageById(videoId);
        coverageImgFilePath += coverageImgName; //得到完整的文件路径
        FileInputStream fis = null;
        response.setContentType("image/gif");
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(coverageImgFilePath);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 查看视频
     * @param videoURL
     * @param request
     * @param response
     */
    @RequestMapping("/getVideoByVideoURL")
    public void getVideoById(@RequestParam("videoURL")String videoURL, HttpServletRequest request, HttpServletResponse response) {
        String videoFilePath = "D:/dStationData/video/";
        videoFilePath += videoURL; //得到完整的文件路径
        //获取从那个字节开始读取文件
        String rangeString = request.getHeader("Range");
        //获取响应的输出流
        try {
            OutputStream outputStream = response.getOutputStream();
            File file = new File(videoFilePath);
            if(file.exists()){
                RandomAccessFile targetFile = new RandomAccessFile(file, "r");
                long fileLength = targetFile.length();
                //播放
                if(rangeString != null){

                    long range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                    //设置内容类型
                    response.setHeader("Content-Type", "video/mp4");
                    //设置此次相应返回的数据长度
                    response.setHeader("Content-Length", String.valueOf(fileLength - range));
                    //设置此次相应返回的数据范围
                    response.setHeader("Content-Range", "bytes "+range+"-"+(fileLength-1)+"/"+fileLength);
                    //返回码需要为206，而不是200
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    //设定文件读取开始位置（以字节为单位）
                    targetFile.seek(range);
                }else {//下载

                    //设置响应头，把文件名字设置好
                    response.setHeader("Content-Disposition", "attachment; filename="+videoURL);
                    //设置文件长度
                    response.setHeader("Content-Length", String.valueOf(fileLength));
                    //解决编码问题
                    response.setHeader("Content-Type","application/octet-stream");
                }

                byte[] cache = new byte[1024 * 300];
                int flag;
                while ((flag = targetFile.read(cache))!=-1){
                    outputStream.write(cache, 0, flag);
                }
            }else {
                String message = "file:"+videoURL+" not exists";
                //解决编码问题
                response.setHeader("Content-Type","application/json");
                outputStream.write(message.getBytes(StandardCharsets.UTF_8));
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            System.out.println("客户端断开数据！");
        }
    }

    /**
     * 根据视频ID删除视频
     * @return
     */
    @RequestMapping(value = "/removeVideoInfoById")
    @ResponseBody
    public JSONObject removeVideoInfoById(@RequestParam("videoId") long videoId) {
        boolean removeResult = videoService.dropVideoInfoById(videoId);
        System.out.println(removeResult);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("removeResult", removeResult);
        return jsonObject;
    }

    /**
     * 跳转到视频信息修改界面
     * @param videoId
     * @return
     */
    @RequestMapping(value = "modifyVideoInfoByIdPage")
    public String modifyVideoInfoByIdPage(@RequestParam("videoId") long videoId,ModelMap modelMap) {
        VideoInfo videoInfo = videoService.findVideoInfoById(videoId);
        ClassificationInfo subCategory = videoService.findClassificationById(Long.valueOf(videoInfo.getVideoClassId()));
        ClassificationInfo mainCategory = videoService.findClassificationById(subCategory.getPreClassificationId());
        List<TagInfo> tagInfoList = videoService.findTagInfoByVideoId(videoId);
        List<ClassificationInfo> classificationInfoList = classificationService.findAllChildClassification();
        List<TagInfo> labelInfoList = tagService.findAllTagInfo();  //全部的标签信息
        labelInfoList.removeAll(tagInfoList);   //求差集
        modelMap.put("videoInfo", videoInfo);
        modelMap.put("subCategory", subCategory);
        modelMap.put("mainCategory", mainCategory);
        modelMap.put("tagInfoList", tagInfoList);
        modelMap.put("classificationInfoList", classificationInfoList);
        modelMap.put("labelInfoList", labelInfoList);
        System.out.println(labelInfoList);
        return "/main/modifyVideoInfoByIdPage";
    }

    @RequestMapping(value = "/modifyVideoInfo")
    @ResponseBody
    public JSONObject modifyVideoInfo(VideoInfo videoInfo, @RequestParam("labelList")String labelList) {
        JSONObject jsonObject = new JSONObject();
        //1. 首先修改视频信息
        boolean modifyRes = videoService.alterVideoInfo(videoInfo);
        if(modifyRes == false) {
            jsonObject.put("res", "error");
            return jsonObject;
        }
        //2. 删除此视频全部的标签信息
        boolean dropRes = videoService.dropTagInfoByVideoId(videoInfo.getVideoId());
        if(dropRes == false) {
            jsonObject.put("res", "error");
            return jsonObject;
        }
        //3. 查询标签ID并插入标签关系
        String[] strArr = labelList.split("\\|");
        ArrayList<TagInfo> labelInfoList = new ArrayList<TagInfo>();
        TagInfo labelInfo = null;
        for(int i = 0; i < strArr.length; i++) {
            labelInfo = tagService.findTagInfoByTagName(strArr[i]);
            labelInfoList.add(labelInfo);
        }
        System.out.println(labelInfoList);
        boolean saveRes = videoService.addVideoTagInfo(labelInfoList, videoInfo.getVideoId(), new Timestamp(System.currentTimeMillis()));
        if(saveRes == false) {
            jsonObject.put("res", "error");
            return jsonObject;
        }
        jsonObject.put("res", "success");
        return jsonObject;
    }

    /**
     * 视频播放放界面
     */
    @GetMapping("/videoPlayback")
    public String videoPlayback(@RequestParam("videoId")int videoId,@RequestParam("isFree") boolean isFree,
                                HttpSession session,ModelMap modelMap) { //拿到videoId
        //1. 判断用户是否登录，若未登录则跳转到登录界面
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");

        //rocketmq埋点
        sendUserBrowserEvent(userInfo,videoId);


        if(userInfo == null) {
            return "user/loginAndRegister";
        }
        //2. 判断该视频是否为免费视频，若为免费视频则直接跳转到界面
        if(isFree) {
            VideoInfo videoInfo = videoService.findVideoDetailInfoById(videoId);    //视频信息
            List<TagInfo> labelInfoList = tagService.findTagsByVideoId(videoId);    //标签信息
            VideoLikedInfo videoLikedInfo = videoService.findUserIsPraiseVideoByVideoIdAndUserId(videoId,
                    ((UserInfo)session.getAttribute("userInfo")).getUserId());  //当前用户是否点赞了
            if(videoLikedInfo == null) {    //当前用户还未点赞
                modelMap.put("isPraise", 0);
            } else {    //当前用户已经点赞
                modelMap.put("isPraise", 1);
            }
            FollowTableInfo followTableInfo = videoService.findUserIsNoticeUp(videoInfo.getUserId(),
                    ((UserInfo)session.getAttribute("userInfo")).getUserId());
            if(followTableInfo == null) {
                modelMap.put("isNoticed", 0);
            } else {
                modelMap.put("isNoticed", 1);
            }

            CollectionInfo collectionInfo = videoService.findUserIsCollectVideoByUserIDAndVideoID(
                    ((UserInfo)session.getAttribute("userInfo")).getUserId(),videoId
            );
            if(collectionInfo == null) {
                modelMap.put("isCollect", 0);
            } else {    //当前用户已经点赞
                modelMap.put("isCollect", 1);
            }
            CoinOperatedInfo coinOperatedInfo = videoService.findUserIsOperatedCoinByVideoAndUserId(videoId,
                    ((UserInfo)session.getAttribute("userInfo")).getUserId());
            if(coinOperatedInfo == null) {
                modelMap.put("isOperateCoin", 0);
            } else {
                modelMap.put("isOperateCoin", 1);
            }
            List<VideoCommentInfo> commentInfoList = videoService.findCommentInfoListByVideoId(videoId);
            System.out.println(commentInfoList);
            if(commentInfoList.size() == 0) {
                modelMap.put("commentInfoList", null);
            } else {
                modelMap.put("commentInfoList", commentInfoList);
            }
            // 当前视频的投币数量
            int coinNum = videoService.findCoinNumByVideoId(videoId);
            String coinStr = "";
            if (coinNum > 10000){
                float newCoinNum = (float)coinNum/10000;
                DecimalFormat df = new DecimalFormat("0.0");
                coinStr = df.format(newCoinNum) + "w";
            }else{
                coinStr += coinNum;
            }
            modelMap.put("coinNum", coinStr);
            HistoryInfo historyInfo = new HistoryInfo();
            historyInfo.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
            historyInfo.setVideoId(new Long((long)videoId));
            historyInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
            videoService.addHistoryInfo(historyInfo);
            //将当前视频的播放次数加一并且更新数据库
            videoInfo.setVideoViewNum(videoInfo.getVideoViewNum() + 1);
            videoService.alterVideoViewNumByVideoId(videoId);
            modelMap.put("videoInfo", videoInfo);
            modelMap.put("labelInfoList", labelInfoList);
            return "main/video_playback_page";
        }
        //3. 以下为非免费视频，判断用户是否还有免费的次数
        if(((UserInfo)session.getAttribute("userInfo")).getPrivilegetimes() <= 0) { //免费次数不足
            return "redirect:/subscriptionPackage/rechargeWatchTimePage";  //跳转到充值界面，暂时还没写
        } else {    //免费次数足够，则将session以及数据库中用户的免费试用次数 - 1
            ((UserInfo)session.getAttribute("userInfo")).setPrivilegetimes(
                    ((UserInfo)session.getAttribute("userInfo")).getPrivilegetimes() - 1
            );
            userService.alterUserPrivilegetimesByUserId( ((UserInfo)session.getAttribute("userInfo")).getUserId());
        }
        VideoInfo videoInfo = videoService.findVideoDetailInfoById(videoId);    //视频信息
        List<TagInfo> labelInfoList = tagService.findTagsByVideoId(videoId);    //标签信息
        VideoLikedInfo videoLikedInfo = videoService.findUserIsPraiseVideoByVideoIdAndUserId(videoId,
                ((UserInfo)session.getAttribute("userInfo")).getUserId());  //当前用户是否点赞了
        if(videoLikedInfo == null) {    //当前用户还未点赞
            modelMap.put("isPraise", 0);
        } else {    //当前用户已经点赞
            modelMap.put("isPraise", 1);
        }
        CoinOperatedInfo coinOperatedInfo = videoService.findUserIsOperatedCoinByVideoAndUserId(videoId,
                ((UserInfo)session.getAttribute("userInfo")).getUserId());
        if(coinOperatedInfo == null) {
            modelMap.put("isOperateCoin", 0);
        } else {
            modelMap.put("isOperateCoin", 1);
        }
        FollowTableInfo followTableInfo = videoService.findUserIsNoticeUp(videoInfo.getUserId(),
                ((UserInfo)session.getAttribute("userInfo")).getUserId());
        if(followTableInfo == null) {
            modelMap.put("isNoticed", 0);
        } else {
            modelMap.put("isNoticed", 1);
        }

        CollectionInfo collectionInfo = videoService.findUserIsCollectVideoByUserIDAndVideoID(
                ((UserInfo)session.getAttribute("userInfo")).getUserId(),videoId
        );
        if(collectionInfo == null) {
            modelMap.put("isCollect", 0);
        } else {
            modelMap.put("isCollect", 1);
        }
        List<VideoCommentInfo> commentInfoList = videoService.findCommentInfoListByVideoId(videoId);
        if(commentInfoList.size() == 0) {
            modelMap.put("commentInfoList", null);
        } else {
            modelMap.put("commentInfoList", commentInfoList);
        }
        // 当前视频的投币数量
        int coinNum = videoService.findCoinNumByVideoId(videoId);
        String coinStr = "";
        if (coinNum > 10000){
            float newCoinNum = (float)coinNum/10000;
            DecimalFormat df = new DecimalFormat("0.0");
            coinStr = df.format(newCoinNum) + "w";
        }else{
            coinStr += coinNum;
        }
        modelMap.put("coinNum", coinStr);
        HistoryInfo historyInfo = new HistoryInfo();
        historyInfo.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
        historyInfo.setVideoId(new Long((long)videoId));
        historyInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
        videoService.addHistoryInfo(historyInfo);
        //将当前视频的播放次数加一并且更新数据库
        videoInfo.setVideoViewNum(videoInfo.getVideoViewNum() + 1);
        videoService.alterVideoViewNumByVideoId(videoId);
        modelMap.put("videoInfo", videoInfo);
        modelMap.put("labelInfoList", labelInfoList);
        return "main/video_playback_page";
    }

    @RequestMapping("/getVideoCoverageImg")
    public void getVideoCoverageImg(@RequestParam("videoCoverImg")String videoCoverImg, HttpServletRequest request, HttpServletResponse response) {
        String coverageImgFilePath = "D:/dStationData/coverageImg/";
        coverageImgFilePath += videoCoverImg; //得到完整的文件路径
        FileInputStream fis = null;
        response.setContentType("image/gif");
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(coverageImgFilePath);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 用户给视频投币
     * @param videoId
     * @return
     */
    @RequestMapping("/saveCoinOperatedInfo")
    @ResponseBody
    public JSONObject saveCoinOperatedInfo(@RequestParam("userId")long userId,@RequestParam("videoId")long videoId,int isOperateCoin,HttpSession session){

        JSONObject jsonObject = new JSONObject();
        UserInfo userInfo = (UserInfo)session.getAttribute("userInfo");

        //rocketmq埋点
        sendUserBrowserEvent(userInfo,(int)videoId);

        Double userBalance = userInfo.getUserBalance();
        //用户没有投币过进行投币
        if(isOperateCoin == 0) {
            //用户硬币数不足，直接返回提示
            if (userBalance == 0){
                jsonObject.put("res", "lack");
                return jsonObject;
            }
            //进行投币操作
            boolean addResult = videoService.addCoinOperatedInfo(userId,videoId);
            //投币结果返回前端
            if (addResult){
                boolean modifyResult = userService.alterUserBlanceByUserId(userId,1);
                userInfo.setUserBalance(--userBalance);
                //投币状态更改为未投币
                jsonObject.put("res", "add");
            }else{
                jsonObject.put("res", "error");
            }
        } else if(isOperateCoin == 1) {
            //撤销投币操作
            boolean removeRes = videoService.removeCoinOperatedInfo(userId,videoId);
            //撤销投币结果返回前端
            if (removeRes){
                boolean modifyResult = userService.alterUserBlanceByUserId(userId,0);
                userInfo.setUserBalance(++userBalance);
                //投币状态更改为已投币
                jsonObject.put("res", "sub");
            }else{
                jsonObject.put("res", "error");
            }
            jsonObject.put("res", "sub");
        }
        session.removeAttribute("userInfo");
        session.setAttribute("userInfo",userInfo);
        int coinNum = videoService.findCoinNumByVideoId(videoId);
        jsonObject.put("coinNum", coinNum);
        return jsonObject;
    }



    /**
     * 视频点赞
     * @param videoId
     * @return
     */
    @RequestMapping(value = "/praiseVideo")
    @ResponseBody
    public JSONObject praiseVideo(@RequestParam("videoId")int videoId, HttpSession session) {


        //rocketmq埋点
        sendUserBrowserEvent((UserInfo)session.getAttribute("userInfo"),(int)videoId);

        // 1. 首先查询 用户点赞表 得到现在的 点赞状态
        VideoLikedInfo videoLikedInfo = videoService.findUserIsPraiseVideoByVideoIdAndUserId(videoId,
                ((UserInfo)session.getAttribute("userInfo")).getUserId());
        JSONObject jsonObject = new JSONObject();
        //2. 若现在为null,表示还没有点赞信息
        if(videoLikedInfo == null) {  //插入一条点赞信息
            boolean saveRes = videoService.addUserPraiseVideoInfo(videoId, ((UserInfo)session.getAttribute("userInfo")).getUserId(), new Timestamp(System.currentTimeMillis()));
            jsonObject.put("res", "add");   //点赞
        } else {    //删除点赞消息
            boolean removeRes = videoService.dropUserPraiseVideoInfo(videoId, ((UserInfo)session.getAttribute("userInfo")).getUserId());
            jsonObject.put("res", "sub");   //点赞
        }
        //3. 查询现在的点赞数量，更新前台界面
        long praiseNum = videoService.findPraiseNumByVideoId(videoId);
        jsonObject.put("praiseNum", praiseNum);
        return jsonObject;
    }

    /**
     * 关注/取消关注
     * @return
     */
    @RequestMapping("/noticedUp")
    @ResponseBody
    public JSONObject noticedUp(@RequestParam("followUserId") Long followUserId,HttpSession session) {
        // 1. 首先查询 用户关注表 得到现在的 关注状态
        FollowTableInfo followTableInfo = videoService.findUserIsNoticeUp(followUserId, ((UserInfo)session.getAttribute("userInfo")).getUserId());
        //2. 若现在为null,表示还没有关注信息
        JSONObject jsonObject = new JSONObject();
        if(followTableInfo == null) {  //插入一条关注信息
            boolean addRes = videoService.addUserIsNoticeUpInfo(followUserId, ((UserInfo)session.getAttribute("userInfo")).getUserId(),
                    new Timestamp(System.currentTimeMillis()));
            jsonObject.put("res", "add");   //关注
        }else{   //没有关注，则修改为关注状态
            boolean removeResult = videoService.dropUserIsNoticeUpInfo(followUserId, ((UserInfo)session.getAttribute("userInfo")).getUserId());
            jsonObject.put("res", "sub");
        }
        return jsonObject;
    }

    private void sendUserBrowserEvent(UserInfo userInfo, int videoId) {

        //如果用户尚未登陆
        if(Objects.isNull(userInfo)){
            return;
        }
        MqMessage mqMessage=new MqMessage(userInfo.getUserId(),videoId,1,new Timestamp(System.currentTimeMillis()));

        try {
            browserMqProducer.messageSendAsync(MQConstant.RECOMMEND_TOPIC,MQConstant.RECOMMEND_USER_BROWSER_TAG, UUID.randomUUID().toString(),mqMessage);
        }catch (Exception e){
            e.printStackTrace();
            log.info("发送失败");
        }
        log.info("发送成功");

    }
}
